package com.ellen.mac.chatdemo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.AVIMConversationsQuery;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.callback.AVIMConversationCallback;
import com.avos.avoscloud.im.v2.callback.AVIMConversationCreatedCallback;
import com.avos.avoscloud.im.v2.callback.AVIMConversationQueryCallback;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.ellen.mac.chatdemo.R;
import com.ellen.mac.chatdemo.activity.ChatNewRoomAct;
import com.ellen.mac.chatdemo.activity.NewChatRoomAct;
import com.ellen.mac.chatdemo.adpter.ListConversationAdpter;
import com.ellen.mac.chatdemo.comment.BaseApp;
import com.ellen.mac.chatdemo.model.AllConversation;
import com.ellen.mac.chatdemo.utils.ChatKit;
import com.ellen.mac.chatdemo.utils.LogUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by j on 2017/12/7.
 */

public class AllGroupFragment extends Fragment {
    Unbinder unbinder;
    List<AllConversation> data;
    private ListConversationAdpter itemAdapter;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.rv_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.group_name)
    EditText groupName;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.findgroupall_fragment, container, false);
        unbinder = ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }
    private void initView(){
        GridLayoutManager layoutManage = new GridLayoutManager(getActivity(), 1);
        mRecyclerView.setLayoutManager(layoutManage);

        data = new ArrayList<>();
        itemAdapter = new ListConversationAdpter(R.layout.userinfo_item, data);
        mRecyclerView.setAdapter(itemAdapter);
        findGroup();
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                findGroup();
            }
        });
        mRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                joinChatRoom(data.get(position).getConversation().getConversationId());
            }
        });
    }

    private void joinChatRoom(final String conversationId) {
        String name = ChatKit.getInstance().getCurrentUserId();

        ChatKit.getInstance().getClient().getChatRoom(conversationId).addMembers(Arrays.asList(name), new AVIMConversationCallback() {
            @Override
            public void done(AVIMException e) {
                Intent intent = new Intent(getContext(), ChatNewRoomAct.class);
//                Intent intent = new Intent(getContext(), ChatRoomAct.class);
//                intent.setPackage(getContext().getPackageName());
//                intent.setAction(BaseApp.CONVERSATION_ITEM_CLICK_ACTION);
//                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.putExtra(BaseApp.CONVERSATION_ID, conversationId);
                startActivity(intent);
            }
        });

    }


    @OnClick({R.id.btn_creat})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.btn_creat:
                createGroup(groupName.getText().toString());
                break;
        }
    }
    private void findGroup() {
        AVIMConversationsQuery query   = ChatKit.getInstance().getClient().getConversationsQuery();
        query.setQueryPolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.limit(50);
        query.whereEqualTo("tr", false);
        query.findInBackground(new AVIMConversationQueryCallback(){
            @Override
            public void done(List<AVIMConversation> list, AVIMException e) {
            if(e !=null){
                return;
            }
            data.clear();
           for(int i=0;i<list.size();i++){
               AllConversation con = new AllConversation();
               AVIMConversation conversation = list.get(i);
               con.setConversation(conversation);
               if(conversation.getMembers().size() == 2){
                   con.setSingle(true);
               }else{
                   con. setSingle(false);
               }
               data.add(con);
           }
            itemAdapter.setNewData(data);
            itemAdapter.notifyDataSetChanged();
            swipeLayout.setRefreshing(false);
            }
        });
    }

    private void createGroup(String groupName) {
        ChatKit.getInstance().getClient().createConversation(new ArrayList<String>(), groupName, null, false, true,
            new AVIMConversationCreatedCallback() {
                @Override
                public void done(AVIMConversation conversation, AVIMException e) {
                    if (e == null) {
                        Toast.makeText(getContext(), "Room Create Success id is " + conversation.getConversationId(), Toast.LENGTH_SHORT).show();
                        //todo 跳转到聊天室
                        Intent intent = new Intent(getContext(), NewChatRoomAct.class);
                        intent.setPackage(getContext().getPackageName());
                        intent.putExtra(BaseApp.CONVERSATION_ID, conversation.getConversationId());
                        startActivity(intent);
                    }else{
                        LogUtils.logException(e);
                    }
                }
            });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
